﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Isis.Helpers.Interfaces;
using Microsoft.VisualBasic.Devices;

namespace Isis.Helpers.Impl
{
    public class ServerInfoHelper : IServerInfoHelper
    {
        public IEnumerable<int> GetProcessIds()
        {
            return Process.GetProcesses().Select(p => p.Id);
        }

        public string GetProcessNameById(int id)
        {
            return Process.GetProcessById(id).ProcessName;
        }

        public long GetProcessPrivateMemorySize64ById(int id)
        {
            return Process.GetProcessById(id).PrivateMemorySize64;
        }

        public double GetTotalRam()
        {
            return new ComputerInfo().TotalPhysicalMemory / 1048576.0;
        }

        public double GetAvailableRam()
        {
            var ramCounter = new PerformanceCounter("Memory", "Available MBytes");

            return ramCounter.NextValue();
        }

        public double GetCpuUsage()
        {
            var cpuCounter = new PerformanceCounter
            {
                CategoryName = "Processor Information",
                CounterName = "% Processor Time",
                InstanceName = "_Total"
            };

            cpuCounter.NextValue();
            Thread.Sleep(50); // need for cpu counter to pick up a value

            return cpuCounter.NextValue() / 100;
        }

        public string GetCpuArchitecture()
        {
            return Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit";
        }

        public int GetProcessThreadCount(int id)
        {
            return Process.GetProcessById(id).Threads.Count;
        }
    }
}